<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>indexDB 前端数据库</title>
</head>
<body>
    <script>
        // var a = 2;
        // const request = 1;
        // index 索引
        var db;
        var request = window.indexedDB.open('blogs', 2);
        // console.log(request);
        request.onerror = function(event) {
            console.log('数据库打开失败');
        }
        request.onsuccess = function(event) {
            db = request.result;
            create();
            // console.log('数据库打开成功');
            // var objectStore = db.createObjectStore('person', {keyPath: 'id'});
        }
        request.onupgradeneeded = function() {
            db = request.result;
            var objectStore;
            if(!db.objectStoreNames.contains('person')) {
                // keyPath 主键 索引就是为了查询更快 doc(id) 详情页 加一个索引
                // 列表 .get() 20 .skip() .limit()
                // 详情页 /detail?id=121212
                objectStore = db.createObjectStore('person', {keyPath: 'id'})
                // /sreach?name=%xiaolang% name部首做索引
                // 123123@qq.com _id 地址
                objectStore.createIndex('name', 'name', {unique: false})
                objectStore.createIndex('email', 'email', {unique: true})
            }
            
        }
        function create() {
            // 事务
            var request = db.transaction(['person'], 'readwrite')
                .objectStore('person')
                .add({id: 1, name: '大佬', age: 24, email: 'xt@tmall.com'})
                request.onsuccess = function() {
                    console.log('数据写入成功');
                }
                request.onerror = function() {
                    console.log('数据写入失败');
                }
        }
      
   </script>
</body>
</html>